package com.study.ceph;


import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import com.amazonaws.util.StringUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;

public class CephMain {

    public static String accessKey = "DPL0TY9V83B5V17MRH02";
    public static String secretKey = "54cRu9cH3V7bvmbih2uljEZDm3dHoGrvnyEpYbAa";

    public static String endpoint = "http://oss.bj1.bigtree.tech";

    public static void main(String[] args) throws IOException {

        AmazonS3 conn = amazonS3();

//        showBluck(conn);

//        upFile(conn);

        bluckList(conn);

//        downloadFile(conn);

        conn.shutdown();

        try {
            bluckList(conn);
        } catch (Exception e) {
            e.printStackTrace();
        }



    }

    static void downloadFile(AmazonS3 conn) throws IOException {
        S3Object object = conn.getObject("btscfp2", "/tmp/图片.jpg");
        object.getKey();//文件名
        S3ObjectInputStream objectContent = object.getObjectContent();
        InputStream inputStream = objectContent.getDelegateStream();

        File file = new File("/Users/zhangbo/Downloads/临时文件/图片下载.jpeg");
        FileOutputStream fileOutputStream = new FileOutputStream(file);

        byte[] bytes = new byte[1024];
        int lenth = -1;
        while ((lenth = inputStream.read(bytes)) != -1) {
            fileOutputStream.write(bytes,0,lenth);
        }
        fileOutputStream.close();
        inputStream.close();
    }


    public static AmazonS3 amazonS3() {
        BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setSignerOverride("S3SignerType");//凭证验证方式
        clientConfig.setProtocol(Protocol.HTTP);//访问协议

        return AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withClientConfiguration(clientConfig)
                .withEndpointConfiguration(
                        new AwsClientBuilder.EndpointConfiguration(//设置要用于请求的端点配置（服务端点和签名区域）
                                endpoint,//我的s3服务器
                                "cn-north-1")).withPathStyleAccessEnabled(true)//是否使用路径方式，是的话s3.xxx.sn/bucketname
                .build();
    }

    /**
     * 显示bluck列表
     *
     * @param conn
     */
    static void bluckList(AmazonS3 conn) {
        /*列出bucket列表*/
        List<Bucket> buckets = conn.listBuckets();
        for (Bucket bucket : buckets) {
            System.out.println("bucket name:" + bucket.getName() + "\t" +
                    StringUtils.fromDate(bucket.getCreationDate()));
        }
    }

    /*显示bluck的文件明细*/
    static void showBluck(AmazonS3 conn) {
        /*列出bucket的内容*/
        ObjectListing objects = conn.listObjects("btscfp2");
        System.out.println("开始输出btscfp2的内容");
        do {
            for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
                System.out.println("name:" + objectSummary.getKey() + "\t" +
                        objectSummary.getSize() + "\t" +
                        StringUtils.fromDate(objectSummary.getLastModified()));
            }
            objects = conn.listNextBatchOfObjects(objects);
        } while (objects.isTruncated());
        System.out.println("输出完成！");
    }

    /*上传一个文件*/
    private static void upFile(AmazonS3 conn) {
        /*新建一个对象*/
        System.out.println("开始上传文件");
        File file = new File("/Users/zhangbo/Downloads/临时文件/图片.jpeg");
        System.out.println(file.length());

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(getFileBytes(file));
        try {
            conn.putObject("btscfp2", "/tmp/图片.jpg", byteArrayInputStream, new ObjectMetadata());
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("文件上传完成");
    }

    public static byte[] getFileBytes(File file) {
        byte[] buffer = null;
        FileInputStream fis;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

}
